/*
 * @Author: LAPTOP-STS5K12N\icey 2237665219@qq.com
 * @Date: 2025-01-30 15:19:15
 * @LastEditors: LAPTOP-STS5K12N\icey 2237665219@qq.com
 * @LastEditTime: 2025-01-30 16:08:37
 * @FilePath: \Buzzer\Bsp\src\bsp.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/********************************************************************************
 * @file    mq_2.c
 * @author  your name
 * @brief
 *******************************************************************************/

/* Includes ------------------------------------------------------------------*/
#include "mq_2.h"
#include <math.h>
#include "adc.h"
/* Private macro -------------------------------------------------------------*/
#define VCC 5.0f                // 传感器工作电压
#define RL 5.0f                 // 负载电阻（单位：kΩ）
#define R0 10.0f                // 传感器在洁净空气中的电阻值（单位：kΩ）
#define ADC_RESOLUTION 65535.0f // 16位ADC的分辨率

// 校准参数（以甲烷为例）
#define A 0.4f
#define B -0.42f
/* Private function prototypes ----------------------------------------------*/

/* Private functions --------------------------------------------------------*/

/* Private variables --------------------------------------------------------*/

/* Public variables ---------------------------------------------------------*/

/* Public functions ---------------------------------------------------------*/

/*
    @brief MQ2 结构体
*/
static MQ2_t g_MQ2_vars;

// 读取MQ-2的ADC值
uint32_t read_mq2_adc(void)
{
    uint32_t adc_value = 0;
    HAL_ADC_Start(&hadc1);
    if (HAL_ADC_PollForConversion(&hadc1, 100) == HAL_OK)
    {
        adc_value = HAL_ADC_GetValue(&hadc1);
    }
    HAL_ADC_Stop(&hadc1);
    return adc_value;
}

/**
 * @brief 计算气体浓度
 *
 * @param adc_value
 * @return float
 *
 * @author XX
 * @date 2025-01-30
 * @copyright Copyright (c) 2025
 * @version
 *   V1.0  2025-01-30  XX    First release
 */
float calculate_gas_concentration(uint32_t adc_value)
{
    // 将ADC值转换为电压
    float v_out = (adc_value * 5.0f) / ADC_RESOLUTION; // 假设参考电压为3.3V

    // 计算传感器电阻 Rs
    float rs = ((VCC - v_out) / v_out) * RL;

    // 计算 Rs/R0 比值
    float ratio = rs / R0;

    // 计算气体浓度
    float g = A * pow(ratio, B);

    return g;
}

/**
 * @brief 获取 MQ2 结构体
 * 
 * @return MQ2_t*
 * 
 * @author XX
 * @date 2025-01-30
 * @copyright Copyright (c) 2025 
 * @version
 *   V1.0  2025-01-30  XX    First release
 */
MQ2_t *Get_MQ2_Vars(void)
{
    return &g_MQ2_vars;
}
/************************ (C) COPYRIGHT Your Company *****END OF FILE****/
